/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.gateway.core.filter;

import com.github.xiaoymin.gateway.core.RouteDispatcher;
import com.github.xiaoymin.gateway.core.auth.ServletGatewayAuthentication;
import com.github.xiaoymin.gateway.core.pojo.ServiceRoute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/***
 *
 * @since:servlet-gateway-spring-boot-starter 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/10/29 20:06
 */
public class ServletGatewayRouteProxyFilter implements Filter {
    private final RouteDispatcher routeDispatcher;
    private final ServletGatewayAuthentication servletGatewayAuthentication;
    Logger logger= LoggerFactory.getLogger(ServletGatewayRouteProxyFilter.class);

    /**
     * 狗仔ProxyHttpFilter 对象实例
     * @param routeDispatcher 执行器对象
     * @param servletGatewayAuthentication 权限校验对象
     */
    public ServletGatewayRouteProxyFilter(RouteDispatcher routeDispatcher, ServletGatewayAuthentication servletGatewayAuthentication) {
        this.routeDispatcher = routeDispatcher;
        this.servletGatewayAuthentication = servletGatewayAuthentication;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        Optional<ServiceRoute> serviceRouteOptional=routeDispatcher.assertServletRequest(request);
        if (serviceRouteOptional.isPresent()){
            logger.info("转发目标服务，地址:{}",request.getRequestURI());
            if (servletGatewayAuthentication.required()){
                if (servletGatewayAuthentication.auth(servletRequest,servletResponse)){
                    routeDispatcher.execute(request,response,serviceRouteOptional.get());
                }else{
                    servletGatewayAuthentication.failedHandle(servletRequest,servletResponse);
                }
            }else{
                routeDispatcher.execute(request,response,serviceRouteOptional.get());
            }
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }


    @Override
    public void destroy() {

    }

}
